import 'package:flutter/material.dart';
import 'package:flutter_demo1/navigator/hi_navigator.dart';
import 'package:flutter_demo1/page/favorite_page.dart';
import 'package:flutter_demo1/page/home_page.dart';
import 'package:flutter_demo1/page/profile_page.dart';
import 'package:flutter_demo1/page/ranking_page.dart';
import 'package:flutter_demo1/util/color.dart';

class BottomNavigator extends StatefulWidget {
  const BottomNavigator({super.key});

  @override
  State<BottomNavigator> createState() => _BottomNavigatorState();
}

class _BottomNavigatorState extends State<BottomNavigator> {
  final _defaultColor = Colors.grey;
  final _activeColor = primary;
  int _currentIndex = 0;
  int initialPage = 0;
  late final PageController _pageController = PageController(
    initialPage: initialPage,
  );
  late List<Widget> _pages;
  static bool _hashBuild = false;

  @override
  Widget build(BuildContext context) {
    //初始化底部
    _pages = [
      HomePage(onJumpTo: (index) => _onJumpTo(index)),
      RankingPage(),
      FavoritePage(),
      ProfilePage(),
    ];
    //判断是否是首次构建
    if (!_hashBuild) {
      //首次构建也通知切换,这样就不依赖页面切换时候的通知了
      HiNavigator.getInstance().onButtonTabChange(initialPage, _pages[0]);
      _hashBuild = true;
    }
    return Scaffold(
      body: PageView(
        controller: _pageController,
        onPageChanged: (index) => _onJumpTo(index, isOnPageChanged: true),
        //页面默认是可以滚动的,设置上以后不会滚动
        physics: NeverScrollableScrollPhysics(),
        children: _pages,
      ),
      //底部导航按钮
      bottomNavigationBar: BottomNavigationBar(
        //设置上以后,底部按钮固定并且不会放大缩小
        type: BottomNavigationBarType.fixed,
        //底部bar选中那个按钮的索引
        currentIndex: _currentIndex,
        onTap: (index) => _onJumpTo(index),
        selectedItemColor: _activeColor,
        items: [
          _bottomItem("首页", Icons.home, 0),
          _bottomItem("排行榜", Icons.local_fire_department, 1),
          _bottomItem("收藏", Icons.favorite, 2),
          _bottomItem("我的", Icons.live_tv, 3),
        ],
      ),
    );
  }

  BottomNavigationBarItem _bottomItem(String s, IconData icon, int i) {
    return BottomNavigationBarItem(
      icon: Icon(icon, color: _defaultColor),
      activeIcon: Icon(icon, color: _activeColor),
      label: s,
    );
  }

  //方法共用的,通过参数判断是哪个地方使用的
  _onJumpTo(int index, {bool isOnPageChanged = false}) {
    if (!isOnPageChanged) {
      //让 PageView展示对应 tab页
      _pageController.jumpToPage(index);
    } else {
      HiNavigator.getInstance().onButtonTabChange(index, _pages[index]);
    }
    setState(() {
      //控制选中一个tab
      _currentIndex = index;
    });
  }
}
